<template>
  <div style="display: inline-block;">
    <el-button type="primary" @click="editUser()">{{$t('table.edit')}}</el-button>
    <el-dialog :visible.sync="dialogTableVisible" :title="$t('table.edit')" width="970px" @close="close">
      <el-form ref="row_data" label-position="left" label-width="auto" style="width: 400px; margin-left:50px;text-align: left">
        <el-form-item v-if="row_data.is_sup_admin !== 1" :label="$t('authority.username')" prop="username">
          <el-input v-model="row_data.username" :disabled="undisabled" />
        </el-form-item>
        <el-form-item v-if="row_data.is_sup_admin !== 1" :label="$t('authority.authority')" prop="shop_name">
          <el-select
            v-model="row_data.role_id"
            class="filter-item"
            
            style="width: 100%">
            <el-option
              v-for="(item, index) in shop_role"
              :key="index"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('authority.nickname')" prop="nickname">
          <el-input v-model="row_data.nickname" />
        </el-form-item>
        <!-- <el-form-item :label="$t('authority.phone')" prop="phone">
          <el-input v-model="row_data.phone" :disabled="undisabled" />
        </el-form-item> -->
        <el-form-item :label="$t('login.password')" prop="password"   v-if="row_data.is_sup_admin !== 1">
          <el-input
            :type="passwordType"
            v-model="password"
            
            name="password"
            auto-complete="on"
            style="width: 200px"
            @keyup.enter.native="handleLogin">
            <span slot="prefix" class="svg-container">
              <svg-icon icon-class="password"/>
            </span>
            <span slot="suffix" class="show-pwd" @click="showPwd">
              <svg-icon icon-class="eye"/>
            </span>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('table.avatar')" prop="head_img">
          <!--<el-alert-->
          <!--title="建议图片长宽比为1:1"-->
          <!--type="warning"-->
          <!--show-icon-->
          <!--close-text="知道了"/>-->
          <el-upload
            :show-file-list="false"
            :on-success="imgSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadImg"
            :multiple="false"
            action=""
            class="avatar-uploader">
            <img v-if="row_data.head_img" :src="row_data.head_img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item :label="'状态'" prop="phone">
          <el-switch :active-value="1" :inactive-value="0" v-model="row_data.status"/>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="submitForm()">{{$t('table.complete')}}</el-button>
          <el-button @click="close()">{{$t('table.cancel')}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
import store from '@/store'
import { edit } from '@/api/user/admin_user'
import { client } from '@/utils/alioss'
// import { getShopRoleList } from '@/api/shop_admin_auth/shopRole'
import { getShopRoleList } from '@/api/shop_admin_auth/shopRole'

export default {
  name: 'DragDialogDemo',
  directives: { elDragDialog },
  props: {
    row_data: {
      type: Object,
      default: function() {
        return null
      }
    }
  },
  data() {
    return {
      dialogTableVisible: false,
      imgtype: "data:image/jpg;base64,",
      undisabled: true,
      password: null,
      data1: {},
      face_pic :"",
      base64 : "",
      shop_role: [
        {
          value: 2,
          label: '客服管理员'
        },
        {
          value: 1,
          label: '管理员'
        }
      ],
      passwordType: 'password',
      shop_role: []
    }
  },
  methods: {
    editUser() {
      this.dialogTableVisible = true
      this.get_shop_role_list()
    },
    get_shop_role_list() {
      getShopRoleList(store.getters.token).then(response => {
        console.log(response.data.data)
        this.shop_role = response.data.data
      })
      // getShopRoleList(store.getters.token).then(res => {
      //   this.shop_role = res.data.list.data
      // })
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
    },
    uploadImg(file) {
      const that = this;
      const fileName = "meirijiemi" + file.file.uid;
      client()
        .put(fileName, file.file)
        .then((res) => {
          // this.$set(that.face_pic, res.url);
          this.row_data.head_img = res.url;
          // that.$message.success('图片上传成功！')
        })
        .catch((err) => {
          // that.$message.error('图片上传失败，原因：' + err)
        });

        // 获取base64
      var reader = new FileReader();
      // 创建一个img对象
      var img = new Image();
      reader.readAsDataURL(file.file);
      reader.onload = (e) => {
        // this.base64 = reader.result.split(",")[1];
        this.base64type = reader.result.split(",")[0];

        img.src = e.target.result;
        // base64地址图片加载完毕后执行
        img.onload = function () {
          // 缩放图片需要的canvas（也可以在DOM中直接定义canvas标签，这样就能把压缩完的图片不转base64也能直接显示出来）
          var canvas = document.createElement("canvas");
          var context = canvas.getContext("2d");
          // 图片原始尺寸
          var originWidth = this.width;
          that.widthsize = originWidth;
          var originHeight = this.height;
          that.heightsize = originHeight;
           

          // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
          var maxWidth = 300,
            maxHeight = 300;
          // 目标尺寸
          var targetWidth = originWidth,
            targetHeight = originHeight;
          // 图片尺寸超过最大尺寸的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更改宽度，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(
                maxWidth * (originHeight / originWidth)
              );
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(
                maxHeight * (originWidth / originHeight)
              );
            }
          }
          // 对图片进行缩放
          canvas.width = targetWidth;
          // console.log( canvas.width,' canvas.width')
          canvas.height = targetHeight;
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight);
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight);
          /* 第一个参数是创建的img对象；第二三个参数是左上角坐标，后面两个是画布区域宽高*/
          // 压缩后的base64文件
           that.base64 = canvas.toDataURL("image/jpeg", 0.92);
          // = newUrl.split(",")[1];
          // console.log(that.row_data.head_img,'this,base')
          // that.face_pic = that.base64;
          // that.base64type = newUrl.split(",")[0];
          // console.log(newUrl, '0000000000000000000000000000000')
        };
      };
    },
    beforeAvatarUpload(file) {
      const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/gif')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error(this.$t("validation.img_tip1"))
        return false
      }
      if (!isLt2M) {
        this.$message.error(this.$t("validation.img_tip2"))
        return false
      }
      return isJPG && isLt2M
    },
    imgSuccess(res, file) {
      this.row_data.head_img = res.url
      // console.log(this.row_data.main_img)
    },
    submitForm() {
      this.data1.id = this.row_data.id
      this.data1.nickname = this.row_data.nickname
      this.data1.password = this.password
      this.data1.head_img = this.base64
      this.data1.status = this.row_data.status
      this.data1.role_id = this.row_data.role_id
      console.log(this.data1, 'this.data1')
      console.log(this.row_data.nickName, 'this.row_data.nickName')
      edit(store.getters.token, this.data1).then(res => {
        if (res.data.status === true) {
          this.$message({
            message:this.$t('table.edit_complete'),
            type: 'success'
          })
        } else {
          this.$message.error(this.$t('table.edit_fail'))
        }
        this.close()
      })
    },
    close() {
      this.$emit('getLists')
      this.dialogTableVisible = false
    }
  }
}
</script>
<style>
  .avatar{
    width: 180px;
    height: 180px;
    border-radius: 3%;
    /*margin-top: 10px;*/
  }
  .avatar-uploader{
    float: left;
    margin-top: 10px;
  }
</style>
